﻿using System.Data;
using Dommel;
using Microsoft.AspNetCore.Mvc;
using orm.dapper.api.Entities;

namespace orm.dapper.api.Controllers
{
    /// <summary>
    /// Dommel 多表操作
    /// </summary>
    public class MultipleOfDommelController(IDbConnection dbConnection) 
        : DommelBaseController(dbConnection)
    {
        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var order = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                CreateTime = DateTime.Now,
                OrderDetails =
                [
                    new()
                    {
                        ProductName = "事务新增",
                        ProductPrice = 1.1m,
                        CreateTime = DateTime.Now
                    },
                    new()
                    {
                        ProductName = "事务新增2",
                        ProductPrice = 1.1m,
                        CreateTime = DateTime.Now
                    }
                ]
            };

            // 无法直接使用事务（可以手动 new 一个连接实例使用）
            var orderId = Convert.ToInt32(await DbConnection.InsertAsync(order));

            foreach (var detail in order.OrderDetails)
            {
                detail.OrderId = orderId;
            }

            await DbConnection.InsertAllAsync(order.OrderDetails);
            return Ok("Id：" + orderId);
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            // 无法直接使用事务（可以手动 new 一个连接实例使用）
            await DbConnection.DeleteMultipleAsync<OrderDetail>(od => od.OrderId == id);
            await DbConnection.DeleteMultipleAsync<Order>(o => o.Id == id);
            return Ok("Success");
        }

        [HttpGet]
        public async Task<IActionResult> List()
        {
            var lookup = new Dictionary<int, Order>();

            await DbConnection.GetAllAsync<Order, OrderDetail, Order>((o, od) =>
            {
                if (!lookup.TryGetValue(o.Id, out var order))
                {
                    order = o;
                    order.OrderDetails = [];
                    lookup.Add(o.Id, order);
                }

                if (od != null)
                {
                    order.OrderDetails.Add(od);
                }
                
                return order;
            });
            
            return Ok(lookup.Values
                .Where(o => o.IsDeleted == false)
                .OrderByDescending(o => o.Id));
        }

        [HttpGet]
        public async Task<IActionResult> Detail(int id)
        {
            // 会自动映射一对多实体关系
            return Ok(await DbConnection.GetAsync<Order, OrderDetail, Order>(id));
        }
    }
}
